package com.oydsoft.service.system.config;

import com.oydsoft.common.model.BaseApiService;
import com.oydsoft.common.model.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends BaseApiService {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //    /**
//     * 基础异常
//     */
//    @ExceptionHandler(BaseException.class)
//    public AjaxResult baseException(BaseException e) {
//        return AjaxResult.error(e.getMessage());
//    }
//
//    /**
//     * 业务异常
//     */
//    @ExceptionHandler(CustomException.class)
//    public AjaxResult businessException(CustomException e) {
//        if (StringUtils.isNull(e.getCode())) {
//            return AjaxResult.error(e.getMessage());
//        }
//        return AjaxResult.error(e.getCode(), e.getMessage());
//    }
//
    @ExceptionHandler(NoHandlerFoundException.class)
    public BaseResponse handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return setResultError(e.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public BaseResponse handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return setResultError(e.getMessage());
    }

    @ExceptionHandler(AccountExpiredException.class)
    public BaseResponse handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return setResultError(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public BaseResponse handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return setResultError(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return setResultError(e.getMessage());
    }
}
